<template>
  <div id="edit">
    <h3>编辑用户</h3>

    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="form.username"></el-input>
      </el-form-item>

      <el-form-item label="密码">
        <el-input v-model="form.password" show-password>
        </el-input>
      </el-form-item>

      <el-form-item label="昵称">
        <el-input v-model="form.nickname"></el-input>
      </el-form-item>

      <el-form-item label="出生日期">
        <el-date-picker
          type="date"
          placeholder="选择日期"
          v-model="form.birthday"
          style="width: 100%;"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="电话">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>

      <el-form-item label="Email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit"
          >保存</el-button
        >
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addUser, updateUser } from '@/api/users'
export default {
  name: 'edit',
  data() {
    return {
      form: {
        username: '',
        password: '',
        nickname: '',
        birthday: '',
        phone: '',
        email: ''
      },
      type: 'add' // 当 type 为 add 时是添加用户信息。为 update 时是修改用户信息
    }
  },
  created() {
    //methods和data已经初始化,常用于操作数据，发起ajax请求
    console.log(this.$route)
    const { userInfo } = this.$route.params
    if (userInfo) {
      ;(this.type = 'update'), (this.form = userInfo)
    }
  },
  methods: {
    onSubmit() {
      if (typeof this.form.birthday !== 'number') {
        this.form.birthday = this.form.birthday.getTime()
      }
      console.log('submit!', this.form.birthday)
      if (this.type === 'add') {
        addUser(this.form).then(res => {
          console.log(res)
          this.$message({
            message: '成功添加用户信息',
            type: 'success'
          })
        })
      } else {
        updateUser(this.form).then(res => {
          console.log(res)
          this.$message({
            message: '成功修改用户信息',
            type: 'success'
          })
        })
        this.$router.back()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
h3 {
  margin-bottom: 20px;
}
</style>
